package com.ybkj.o2o.zhuanxian.controller.res;

import com.ybkj.o2o.zhuanxian.common.DataGrid;
import com.ybkj.o2o.zhuanxian.common.error.Error;
import com.ybkj.o2o.zhuanxian.common.error.ErrorConstantV4;
import com.ybkj.o2o.zhuanxian.common.error.ResultTransport;
import com.ybkj.o2o.zhuanxian.entity.Car;
import com.ybkj.o2o.zhuanxian.entity.Line;
import com.ybkj.o2o.zhuanxian.manager.CarAndLineManager;
import com.ybkj.o2o.zhuanxian.manager.LineManager;

import com.ybkj.o2o.zhuanxian.service.CarService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("api/line")
public class LineController {

  @Autowired
  private LineManager lineManager;

  @Autowired
  private CarAndLineManager carAndLineManager;

	@Autowired
	private CarService carService;

  private static  final Logger logger = LoggerFactory.getLogger(LineController.class);

  /**
   * 查询该线路的反向线路
   * @param lineId
   * @return
   */
  @RequestMapping("findReturnLine")
  @ResponseBody
  public ResultTransport findReturnLine(@RequestParam(required = false, value = "lineId") Long lineId,
                                        @RequestParam(required = false ,value = "appKey") String appKey){
    //正向线路
    Line line = lineManager.findById(lineId,appKey);
    String[] spotArr = line.getName().split("-");
    StringBuilder sb = new StringBuilder();
    for(int i = spotArr.length - 1;i >= 0;i--){
      sb.append(spotArr[i]);
      if(i > 0){
        sb.append("-");
      }
    }
    List<Line> returnLineList = lineManager.findLineByName(sb.toString(),appKey,line.getCompanyId());
    Line returnLine = null;
    if(returnLineList.size() > 0){
      returnLine = returnLineList.get(0);
    }
    ResultTransport result = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    result.setData(returnLine);
    return result;
  }

  /**
   * 创建线路 .
   * @param companyId       公司id
   * @param companyName     公司名称
   * @param areaId          收费标准id
   * @param jihuoAreaId     寄货id
   * @param baocheAreaId    包车id
   * @param name            线路名称
   * @param startCity       开始城市
   * @param startAddress    开始地址
   * @param endCity         结束城市
   * @param endAddress      结束地址
   * @param appKey          区分系统
   */

  @RequestMapping("createline")
  @ResponseBody
  public ResultTransport createline(
      @RequestParam("companyId") Long companyId,
      @RequestParam("companyName") String companyName,
      @RequestParam("areaId") Long areaId,
      @RequestParam("jihuoAreaId") Long jihuoAreaId,
      @RequestParam("baocheAreaId") Long baocheAreaId,
      @RequestParam("name") String name,
      @RequestParam("startCity") String startCity,
      @RequestParam(required = false,value = "startAddress") String startAddress,
      @RequestParam("endCity") String endCity,
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam("appKey") String appKey,
      @RequestParam(required = false, value = "contactNumber") String contactNumber) {
    ResultTransport response = null;
    try {
      /*
       * boolean success =
       * lineManager.isAlikeLine(companyId,startCity,startAddress,endCity,endAddress); if(success){
       * return ResultTransport.getErrorBy(ErrorConstantV4.ALIKELINE_NOT_CAREATE); }
       */
      boolean success = lineManager.isIpentity(
              companyId,startCity,startAddress,endCity,endAddress,appKey);
      if (success) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ALIKELINE_NOT_CAREATE);
      }
      /* if((startCity+startAddress).equalsIgnoreCase(endCity+endAddress)){
        return ResultTransport.getErrorBy(new Error(
        ErrorConstantV4.PARAM_ERROR.getCode(),"开始地区跟目的地不能完全一样"));
      }*/
      List<Line> temp = lineManager.findLineByName(name,appKey,companyId);
      if (!CollectionUtils.isEmpty(temp)) {
        return  ResultTransport.getErrorBy(
                new Error(ErrorConstantV4.PARAM_ERROR.getCode(),"路线名字已存在"));
      }
      Line line = new Line();
      line.setCompanyId(companyId);
      line.setCompanyName(companyName);
      line.setAreaId(areaId);
      line.setName(name);
      line.setStartCity(startCity);
      line.setStartAddress(startAddress);
      line.setEndCity(endCity);
      line.setEndAddress(endAddress);
      line.setAppKey(appKey);
      line.setBaocheAreaId(baocheAreaId);
      line.setJihuoAreaId(jihuoAreaId);
      line.setCreated(new Date());
      line.setUpdated(new Date());
      line.setContactNumber(null == contactNumber ? null : contactNumber);
      line = lineManager.create(line);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(line);
    } catch (Exception ex) {
      logger.error("createline:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }

    return response;
  }

  /**
   * 多条件分页查询线路 .
   * @param companyId       公司id
   * @param companyName     公司名称
   * @param name            线路名
   * @param startCity       开始城市
   * @param startAddress    开始地址
   * @param endCity         结束城市
   * @param endAddress      结束地址
   * @param page            页数(从1开始)
   * @param rows            每页数量
   * @param appKey          区分系统
   */
  @RequestMapping("findByParam")
  @ResponseBody
  public ResultTransport findByParam(
      @RequestParam(required = false, value = "companyId") Long companyId,
      @RequestParam(required = false, value = "companyName") String companyName,
      @RequestParam(required = false, value = "name") String name,
      @RequestParam(required = false,value = "startCity") String startCity,
      @RequestParam(required = false,value = "startAddress") String startAddress,
      @RequestParam(required = false,value = "endCity") String endCity,
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam(required = false, value = "page") Integer page,
      @RequestParam(required = false,value = "rows") Integer rows,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    try {
      DataGrid<Line> data =
          lineManager.findByParam(companyId, companyName, name, startCity, startAddress, endCity,
              endAddress, page, rows, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(data);
      return response;
    } catch (Exception ex) {
      logger.error("findByParam:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }


  }

  /**
   * 删除线路 .
   * @param id      线路id
   * @param appKey  区分系统
   */
  @RequestMapping("deleteline")
  @ResponseBody
  public ResultTransport deleteline(
      @RequestParam("id") Long id,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    try {
      lineManager.deleteLine(id, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    } catch (Exception ex) {
      logger.error("deleteline:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
    return response;
  }

  /**
   * 根据id和appkey查询单个线路 .
   * @param id      线路id
   * @param appKey  区分系统
   */
  @RequestMapping("findOne")
  @ResponseBody
  public ResultTransport findOne(
      @RequestParam("id") Long id,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    try {
      Line line = lineManager.findById(id, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(line);
      return response;
    } catch (Exception ex) {
      logger.error("findOne:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }
  }

  /**
   * 修改线路 .
   * @param id              线路id
   * @param companyId       公司id
   * @param companyName     公司名称
   * @param areaId          收费标准id
   * @param baocheAreaId    包车id
   * @param jihuoAreaId     寄货id
   * @param name            线路名称
   * @param startCity       开始城市
   * @param startAddress    开始地址
   * @param endCity         结束城市
   * @param endAddress      结束地址
   * @param appKey          区分系统
   */
  @RequestMapping("updateline")
  @ResponseBody
  public ResultTransport updateline(
      @RequestParam("id") Long id,
      @RequestParam(required = false,value = "companyId") Long companyId,
      @RequestParam(required = false, value = "companyName") String companyName,
      @RequestParam(required = false, value = "areaId") Long areaId,
      @RequestParam(required = false,value = "baocheAreaId") Long baocheAreaId,
      @RequestParam(required = false,value = "jihuoAreaId") Long jihuoAreaId,
      @RequestParam(required = false, value = "name") String name,
      @RequestParam(required = false,value = "startCity") String startCity,
      @RequestParam(required = false,value = "startAddress") String startAddress,
      @RequestParam(required = false,value = "endCity") String endCity,
      @RequestParam(required = false, value = "endAddress") String endAddress,
      @RequestParam("appKey") String appKey,
      @RequestParam(required = false, value = "contactNumber") String contactNumber) {
    ResultTransport response = null;
    try {
      Line line = lineManager.findById(id, appKey);
      if (line == null) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ZHUANXIAN_LINE_NOT_EXISTS);
      }
      /*
       * boolean success =
       * lineManager.isUpdateAlikeLine(line.getId(),companyId,startCity,startAddress
       * ,endCity,endAddress); if(success){ return ResultTransport.getErrorBy(new
       * Error(ErrorConstantV4.ALIKELINE_NOT_CAREATE.getCode(),"路线已存在")); }
       */
      boolean success =
            lineManager.isUpdateIpentity(line.getId(),line.getCompanyId(),startCity,
                    startAddress,endCity,endAddress,appKey);
      if (success) {
        return ResultTransport.getErrorBy(
                new Error(ErrorConstantV4.ALIKELINE_NOT_CAREATE.getCode(),"线路已存在"));
      }
      /* if((startCity+startAddress).equalsIgnoreCase(endCity+endAddress)){
      return ResultTransport.getErrorBy(new Error(ErrorConstantV4.PARAM_ERROR.getCode(),
      "开始地区跟目的地不能完全一样"));
      }*/
      List<Line> temps = lineManager.findLineByName(name,appKey,line.getCompanyId());
      boolean flag = false;
      for (Line li : temps) {
        if (!li.getId().equals(id)) {
          flag = true;
          break;
        }
      }
      if (flag) {
        return  ResultTransport.getErrorBy(new Error(
                ErrorConstantV4.PARAM_ERROR.getCode(),"路线名字已存在"));
      }


      line.setCompanyId(companyId != null ? companyId : line.getCompanyId());
      line.setCompanyName(StringUtils.isNotBlank(companyName) ? companyName : line.getCompanyName());
      line.setAreaId(areaId != null ? areaId : line.getAreaId());
      line.setBaocheAreaId(baocheAreaId != null ? baocheAreaId : line.getBaocheAreaId());
      line.setJihuoAreaId(jihuoAreaId != null ? jihuoAreaId : line.getJihuoAreaId());
      line.setAreaId(areaId != null ? areaId : line.getAreaId());
      line.setName(StringUtils.isNotBlank(name) ? name : line.getName());
      line.setStartCity(StringUtils.isNotBlank(startCity) ? startCity : line.getStartCity());
      line.setStartAddress(StringUtils.isNotBlank(startAddress) ? startAddress : line.getStartAddress());
      line.setEndCity(StringUtils.isNotBlank(endCity) ? endCity : line.getEndCity());
      line.setEndAddress(StringUtils.isNotBlank(endAddress) ? endAddress : line.getEndAddress());
      line.setContactNumber(contactNumber);

      lineManager.update(line);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    } catch (Exception ex) {
      logger.error("updateline:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }

    return response;
  }

  /**
   * 根据车辆id和appKey查询线路 .
   * @param carId   车辆id
   * @param appKey  区分系统
   */
  @RequestMapping("findByCar")
  @ResponseBody
  public ResultTransport findByCar(
      @RequestParam(required = true, value = "carId") Long carId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    try {
      List<Line> lines = lineManager.findByCar(carId, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(lines);
      return response;
    } catch (Exception ex) {
      logger.error("findByCar:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }

  }

  /**
   * 根据线路id和appkey查询单条线路 .
   * @param lineId  线路id
   * @param appKey  区分系统
   */
  @RequestMapping("findCarByLine")
  @ResponseBody
  public ResultTransport findCarByLine(
      @RequestParam("lineId") Long lineId,
      @RequestParam("appKey") String appKey) {
    ResultTransport response = null;
    try {
      List<Car> car = lineManager.findCarByLine(lineId, appKey);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      response.setData(car);
      return response;
    } catch (Exception ex) {
      logger.error("findCarByLine:{}",ex);
      response = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
      return response;
    }

  }

  /**
   * 根据开始、结束城市、appkey查询线路 .
   * @param startCity   开始城市
   * @param endCity     结束城市
   * @param appKey      区分系统
   */
  @RequestMapping(value = "findStartEndByLine", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findStartEndByLine(
      @RequestParam(required = false, value = "startCity") String startCity,
      @RequestParam(required = false, value = "endCity") String endCity,
      @RequestParam("appKey") String appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> list = lineManager.findStartEndByLine(startCity, endCity, appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      logger.error("findStartEndByLine:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
    * 查询线路 .
    * @param startCity 开始城市
    * @param startAddress 开始地址
    * @param endCity 结束城市
    * @param isStart 是否开始
    * @param appKey appKey
     */
  @RequestMapping(value = "queryline",method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport queryLine(
          @RequestParam(required = false,value = "startCity") String startCity,
          @RequestParam(required = false,value = "startAddress") String startAddress,
          @RequestParam(required = false,value = "endCity") String endCity,
          @RequestParam("isStart") boolean isStart,
          @RequestParam("appKey")String  appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<Line> list = lineManager.queryline(startCity,startAddress, endCity,isStart,appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      logger.error("queryline:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * 根据城市查询线路 .
   * @param city 城市
   * @param appKey appKey
   */
  @RequestMapping(value = "querylineByCity",method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport querylineByCity(
          @RequestParam("city") String city,
          @RequestParam("appKey")String appKey) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      List<String> list = lineManager.querylineByCity(city,appKey);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(list);
      return instance;
    } catch (Exception ex) {
      logger.error("querylineByCity:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }

  /**
   * .
   * @param startCity 开始城市
   * @param startAddress 开始地址
   * @param endcity 结束城市
   * @param endAddress 结束地址
   * @param appKey appKey
   */
  @RequestMapping(value = "lineisexist")
  @ResponseBody
  public ResultTransport lineIsExist(
          @RequestParam("startCity")String startCity,
          @RequestParam("startAddress")String startAddress,
          @RequestParam("endCity")String endcity,
          @RequestParam("endAddress")String endAddress,
          @RequestParam("appKey")String appKey
  ) {
    try {
      List<Line> list = lineManager.lineIsExist(startCity,startAddress,endcity,endAddress,appKey);
      if (CollectionUtils.isEmpty(list)) {
        return ResultTransport.getErrorBy(ErrorConstantV4.ZHUANXIAN_LINE_NOT_EXISTS);
      } else {
        Map<String,Object> data = new HashMap<>();
        Line line = list.get(0);
        data.put("lineId",line.getId());
        data.put("appKey",line.getAppKey());
        data.put("pincheAreaId",line.getAreaId());
        data.put("baocheAreaId",line.getBaocheAreaId());
        data.put("companyId",line.getCompanyId());
        data.put("companyName",line.getCompanyName());
        data.put("endAddress",line.getEndAddress());
        data.put("endCity",line.getEndCity());
        data.put("jihuoAreaId",line.getJihuoAreaId());
        data.put("name",line.getName());
        data.put("startAddress",line.getStartAddress());
        data.put("startCity",line.getStartCity());

				List<Car> cars = carService.findByParam(line.getId(), line.getName(), line.getCompanyId(), line.getCompanyName(), null, null,
								new Integer[]{Car.CAR_FREE}, null, null, null, null, appKey);
				if(null!=cars) {
					List<Integer> peopleNumbers = new ArrayList<>();
					for (Car car : cars) {
						if(null!=car.getRidepeopleNumber()) {
							peopleNumbers.add(car.getRidepeopleNumber());
						}
					}
					if(cars.size()>1) {
						Collections.sort(peopleNumbers, new Comparator<Integer>() {
							public int compare(Integer o1, Integer o2) {
								return o2 - o1;
							}
						});
					}
					if(!peopleNumbers.isEmpty()) {
						data.put("peopleNumber", peopleNumbers.get(0));
					}
				}

        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(data);
        return instance;
      }
    } catch (Exception ex) {
      logger.error("lineisexist:{}",ex);
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }

  }
  
  /**
   * 根据线路名称分页查询线路(客户端) .
   * @param keyWord   线路名或城市名称
   * @param appKey      区分系统
   * @Param isWX  判断是否是公众号请求(0-不是，1-是)
   */
  @RequestMapping(value = "findLineByParams", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findLineByParams(
      @RequestParam(required = false, value = "keyWord") String keyWord, 
      @RequestParam(required = false, value = "page") Integer page, 
      @RequestParam(required = false, value = "rows") Integer rows,
      @RequestParam("serverUrl") String serverUrl,
      @RequestParam("appKey") String appKey, @RequestParam(required = false, value = "isWX") Integer isWX) {
    if (StringUtils.isBlank(appKey)) {
      return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
    }
    try {
      DataGrid<Map<String, Object>> dataGrid = lineManager.findLineByParams(
          keyWord, page, rows, serverUrl, appKey, isWX);
      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
      instance.setData(dataGrid);
      return instance;
    } catch (Exception ex) {
      ex.printStackTrace();
      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
    }
  }
  
  @RequestMapping(value = "findEndInfoByStartInfo", method = RequestMethod.GET)
  @ResponseBody
  public ResultTransport findEndInfoByStartInfo (
		  @RequestParam(required = true, value = "startCity") String startCity, 
		  @RequestParam(required = true, value = "startAddress") String startAddress,
	      @RequestParam(required = false, value = "page") Integer page, 
	      @RequestParam(required = false, value = "rows") Integer rows,
	      @RequestParam(required = true, value = "serverUrl") String serverUrl,
	      @RequestParam(required = true, value = "appKey") String appKey) {
	    try {
	      DataGrid<Map<String, Object>> dataGrid = lineManager.findEndInfoByStartInfo(startCity, startAddress, page, rows, serverUrl, appKey);
	      ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
	      instance.setData(dataGrid);
	      return instance;
	    } catch (Exception ex) {
	      ex.printStackTrace();
	      return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
	    }
  } 
}
